package com.feihao.calendarTest;

import java.util.Calendar;
import java.util.Scanner;

public class Test2Calendar {

    static Scanner sc = new Scanner(System.in);

    static int year;
    static int month;

    public static void main(String[] args) {
        while (true) {
            System.out.println("请输入年份：");
            String ye = sc.next();
            /*if (ye.matches("\\d{4}")) {
                year = Integer.parseInt(ye);
                break;
            } else {
                System.out.println("年份输入错误，请重新输入");
            }*/
            try {
                year = Integer.parseInt(ye);
                break;
            } catch (NumberFormatException e) {
                System.out.println(e.getMessage() + "年份输入错误，请重新输入");
            }
        }


        while (true) {
            /*if (mon.matches("[1-9]|0[1-9]|1[012]")) {
                month = Integer.parseInt(mon);
                break;
            } else {
                System.out.println("月份输入错误，请重新输入");
            }*/

            System.out.println("请输入月份：");
            String mon = sc.next();

            try {
                month = Integer.parseInt(mon);
            } catch (NumberFormatException e) {
                System.out.println(e);
            }
            if (month > 12 || month < 1) {
                System.out.println("月份输入错误，请重新输入");
            }
            else break;

        }


        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, 1);//calendar获取到的月份实际值0-11；我们这只month-1值，实际就是代表month的值，如设置2月份，实际是3月份

        int day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);  //获取本月最大天数
        int index = cal.get(Calendar.DAY_OF_WEEK); //判断该月第一天是星期几，输出几个空格（返回1-7代表星期天-星期六）

        System.out.println("日" + "\t" + "一" + "\t" + "二" + "\t" + "三" + "\t" + "四" + "\t" + "五" + "\t" + "六" + "\t");
        for (int i = 0; i < index - 1; i++) {
            System.out.print(" " + "\t");
        }

        for (int i = 1; i <= day; i++) {    //输出该月每天，输出七个换行
            System.out.print(i + "\t");
            if ((index - 1 + i) % 7 == 0) {
                System.out.println("");
            }
        }
    }

}
